<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\api\controller;
use think\Db;
class Plan extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');
        extract(input());
        if($user_id != 0){
            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
            if($auth == 112){
                echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
                exit;
            }elseif($auth == 110){
                echo json_encode(['status' => 302, 'msg' => $this->frost]);
                exit;
            }elseif($auth == 1103){
                echo json_encode(['status' => 303, 'msg' => $this->del]);
                exit;
            }
        }

    }


    /**
     * 我的计划(学生老师通用)
     * type：当为学生时，1为主课 2为副课；
     */
    public function myPlans()
    {
        extract(input());
        $auth = Db::table('up_u_user')->where('user_id',$user_id)->value('user_type');
        if(!isset($type)|| empty($type)){
            $type = 1;
        }else{
            if($type != 1 && $type != 2){
                return json_encode(['status'=>0,'msg'=>'参数有误']);
            }
        }
        if(!isset($startdate)|| empty($startdate)){
            $startdate = date('Y-m-d');
        }
        $res = $this->getMyPlans($auth,$user_id,$page,$type,$startdate);
        $plans = $res['plans'];
        $precent = $res['precent'];
        return json_encode(['status'=>200,'msg'=>$plans,'precent'=>$precent]);
    }
    protected function getMyPlans($auth,$user_id,$page,$type,$startdate)
    {
        if($auth == 1){
            $where = [
                'plan_student' => $user_id,
                'plan_online' => 1,
                'plan_type' => $type,
            ];
            $field = 'plan_id,plan_typename,user_username,plan_start_time,plan_end_time,plan_real_start,plan_real_end';
            $field .= ',plan_list,plan_status,plan_way,plan_percent,plan_feedback,plan_comment';
            $plans = Db::table('up_plan_info')->alias('p')
                ->join('up_u_user u','p.plan_teacher=u.user_id','LEFT')
                ->where($where)
                ->field($field)
                ->order('plan_sort asc,plan_start_time ASC')
                ->page ($page,15)
                ->select();
            $all = Db::table('up_plan_info')
                ->where('plan_student',$user_id)
                ->where('plan_online',1)
                ->count();
            $now = Db::table('up_plan_info')
                ->where('plan_student',$user_id)
                ->where('plan_online',1)
                ->where('plan_status',3)
                ->count();
            $precent = round(($now/$all)*100,2);
        }else{
            $where = [
                'plan_teacher' => $user_id,
                'plan_online' => 1,
            ];
            $field = 'plan_id,plan_typename,plan_start_time,plan_end_time,plan_real_start,plan_real_end';
            $field .= ',plan_list,plan_status,plan_way,plan_percent';
            $field .= ',p_name,plan_address,plan_lat,plan_lon,plan_feedback,plan_comment,user_username';
            $plans = Db::table('up_plan_info')->alias('pi')
                ->join('up_plan p','pi.plan_p_id=p.p_id','LEFT')
                ->join('up_u_user u','pi.plan_student=u.user_id','LEFT')
                ->where($where)
                ->whereTime('plan_start_time','between',[$startdate . ' 00:00:00',$startdate . ' 23:59:59'])
                ->field($field)
                ->order('plan_sort asc,plan_start_time ASC')
                ->page ($page,15)
                ->select();
            $precent = Db::table('up_plan_info')
                ->where('plan_teacher',$user_id)
                ->where('plan_online',1)
                ->order('plan_real_end desc')
                ->value('plan_percent');
        }
        $res = [
            'plans' => $plans,
            'precent' => $precent
        ];
        return $res;
    }
    /**
     * 更改上课状态（老师专用）
     */
    public function changePlanStatus()
    {
        extract(input());
        //
        $today = date('Y-m-d H:i:s');
        $data = Db::table('up_plan_info')->where('plan_id',$plan_id)
            ->field('plan_p_id,plan_status,plan_feedback,plan_student,plan_number,plan_typename,plan_real_start,plan_minus')->find();
        if($change_status == 1){ //开始上课
            if($data['plan_status'] == 1){
                $res = Db::table('up_plan_info')->where('plan_id',$plan_id)->update([
                    'plan_real_start' => $today,
                    'plan_status' => 2,
                    'plan_zaitu' => 3,
                    'plan_way' => $way
                ]);
                if($res){
                    return json(['status' => 200, 'msg' => 'ok']);
                }else{
                    return json(['status' => 0, 'msg' => '状态更改失败，请刷新重试！']);
                }
            }else{
                return json_encode(['status'=>0,'msg'=>'只有未上课的才可以开始上课']);
            }
        }elseif ($change_status == 2){
            if($data['plan_status'] == 2){
                //1、算进度
                $all = Db::table('up_plan_info')
                    ->where('plan_p_id',$data['plan_p_id'])
                    ->where('plan_online',1)
                    ->count();
                $now = Db::table('up_plan_info')
                    ->where('plan_p_id',$data['plan_p_id'])
                    ->where('plan_online',1)
                    ->where('plan_status',3)
                    ->count();
                $precent = round((($now+1)/$all)*100,2);
                $realminus = $data['plan_minus'];
                if($data['plan_real_start']){
                    $realminus = (strtotime($today) - strtotime($data['plan_real_start']))/60;
                }
                $res = Db::table('up_plan_info')->where('plan_id',$plan_id)->update([
                    'plan_real_end' => $today,
                    'plan_real_minus' => round($realminus),
                    'plan_status' => 3,
                    'plan_radio' => $plan_radio,
                    'plan_percent' => $precent
                ]);
                if($res){
                    //2、结束就发消息给学生去评价
                    //3、推送
                    try{
                        $con = '；课程编号：' . $data['plan_number'] . '，名字：' . $data['plan_typename'];
                        $nid = allInNotice($this->title2,$this->content2 . $con,2,$data['plan_student'],$plan_id);
                        $this->Jpush(1, $data['plan_student'], $this->title2, ['type'=>2,'nid'=>$nid]);
                    }catch(\Exception $e){

                    }
                    return json(['status' => 200, 'msg' => 'ok']);
                }else{
                    return json(['status' => 0, 'msg' => '状态更改失败，请刷新重试！']);
                }
            }else{
                return json_encode(['status'=>0,'msg'=>'只有进行中的才可以结束上课']);
            }
        }else{
            return json_encode(['status'=>0,'msg'=>'未知参数']);
        }
    }
    public function updateMapPic()
    {
        $update = [];
        $plan_id = $_POST['plan_id'];
        if(isset($_POST['plan_audio']) && $_POST['plan_audio']){
            $update['plan_radio'] = $_POST['plan_audio'];
        }
        if(isset($_POST['plan_map']) && $_POST['plan_map']){
            $update['plan_map'] = $_POST['plan_map'];
        }
        if(isset($_POST['plan_back_map']) && $_POST['plan_back_map']){
            $update['plan_back_map'] = $_POST['plan_back_map'];
        }
        if(isset($_POST['plan_zaitu']) && $_POST['plan_zaitu']){
            $update['plan_zaitu'] = $_POST['plan_zaitu'];
        }
        if(isset($_POST['plan_tea_lat']) && $_POST['plan_tea_lat']){
            $update['plan_tea_lat'] = $_POST['plan_tea_lat'];
            $update['plan_tea_lon'] = $_POST['plan_tea_lon'];
        }

        $res = Db::table('up_plan_info')->where('plan_id',$plan_id)->update($update);
        if($res){
            return json(['status' => 200, 'msg' => 'ok']);
        }else{
            return json(['status' => 100, 'msg' => '更新失败']);
        }
    }
    /**
     * 老师反馈
     *
     */
    public function planFeed()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $data = Db::table('up_plan_info')->where('plan_id',$plan_id)
            ->field('plan_p_id,plan_status,plan_feedback,plan_student,plan_number,plan_typename')->find();
        if($data['plan_status'] == 3 && $data['plan_feedback'] == 1){
            $res = Db::table('up_plan_info')->where('plan_id',$plan_id)->update([
                'plan_feedback' => 2,
                'plan_feed_content' => $content,
                'plan_feed_time' => $today
            ]);
            if($res){
                //2、反馈完发消息给学生结果
                //3、推送
                try{
                    $con = '课程编号：' . $data['plan_number'] . '，名字：' . $data['plan_typename'] . '，反馈内容：';
                    $nid = allInNotice($this->title3,$this->content3 . $con . $content,3,$data['plan_student'],$plan_id);
                    $this->Jpush(1, $data['plan_student'], $this->title3, ['type'=>3,'nid'=>$nid]);
                }catch(\Exception $e){

                }
                return json(['status'=>200,'msg'=>'ok']);
            }else{
                return json(['status'=>0,'msg'=>'状态更改失败，请刷新重试']);
            }
        }else{
            return json(['status'=>0,'msg'=>'只有已结束未反馈的才可以反馈']);
        }

    }
    /**
     * 学生评价
     *
     */
    public function planComment()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $data = Db::table('up_plan_info')->where('plan_id',$plan_id)
            ->field('plan_p_id,plan_status,plan_comment,plan_teacher,plan_number,plan_typename')->find();
        if($data['plan_status'] == 3 && $data['plan_comment'] == 1){
            $res = Db::table('up_plan_info')->where('plan_id',$plan_id)->update([
                'plan_comment' => 2,
                'plan_comment_star' => $star,
                'plan_comment_content' => $content,
                'plan_comment_time' => $today
            ]);
            if($res){
                //1、先把这条消息改掉，已经评价了
                Db::table('up_notice')->where('n_id',$n_id)->update([
                    'n_status' => 2
                ]);
                //2、评价完发消息给老师
                //3、推送
                try{
                    $con = '课程编号：' . $data['plan_number'] . '，名字：' . $data['plan_typename'] . '，评价星级：';
                    $nid = allInNotice($this->title4,$this->content4 . $con. $star,4,$data['plan_teacher'],$plan_id);
                    $this->Jpush(1, $data['plan_teacher'], $this->title3, ['type'=>4,'nid'=>$nid]);
                }catch(\Exception $e){

                }
                $back = [
                    'plan_comment_star' => $star,
                    'plan_comment_content' => $content
                ];
                return json(['status'=>200,'msg'=>$back]);
            }else{
                return json(['status'=>0,'msg'=>'状态更改失败，请刷新重试']);
            }
        }else{
            return json(['status'=>0,'msg'=>'只有已结束未评价的才可以评价']);
        }

    }
    //------------------------------------------------------------------
    /**
     * 我的钢琴课（练习专用）
     */
    public function MyPractice()
    {
        extract(input());
        if(isset($today) && $today){
            $pra_date = $today;
        }else{
            $pra_date = date('Y-m-d');
        }
        $where = [
            'pra_student' => $user_id,
            'pra_online' => 1,
            'pra_date' => $pra_date,
        ];
        $field = 'pra_id,pra_url,pra_status,pra_name,pra_p_id';
        $data = Db::table('up_plan_practice')
            ->where($where)
            ->field($field)
            ->select();
        $res = [];
        $all_have = Db::table('up_plan_practice')
            ->where('pra_student',$user_id)
            ->where('pra_online',1)
            ->field($field)
            ->find();
        if($all_have){
            $res['pra_name'] = Db::table('up_plan_practice')
                ->where($where)
                ->column('pra_name');
            $res['pra_minus'] = Db::table('up_plan_practice')
                ->where('pra_p_id',$all_have['pra_p_id'])
                ->where('pra_date',$pra_date)
                ->where('pra_online',1)
                ->sum('pra_minus');
            $praminus1 = Db::table('up_plan_practice')
                ->where('pra_p_id',$all_have['pra_p_id'])
                ->where('pra_online',1)
                ->sum('pra_all_minus');
            $infominus2 = Db::table('up_plan_info')
                ->where('plan_p_id',$all_have['pra_p_id'])
                ->where('plan_online',1)
                ->sum('plan_real_minus');
            $res['pra_all_minus'] = $praminus1 + $infominus2;
            $res['pra_days'] = Db::table('up_plan_practice')
                ->where('pra_p_id',$all_have['pra_p_id'])
                ->where('pra_status',2)
                ->where('pra_online',1)
                ->group('pra_date')
                ->count();
            $res['pra_times'] = Db::table('up_plan_practice')
                ->where('pra_p_id',$all_have['pra_p_id'])
                ->where('pra_online',1)
                ->sum('pra_times');
        }
        return json(['status'=>200,'msg'=>$data,'res'=>$res]);
    }
    /**
     * 练习结束
     */
    public function endPractice()
    {
        extract(input());
        $data = Db::table('up_plan_practice')
            ->where('pra_id',$pra_id)
            ->find();
        $all = Db::table('up_plan_practice')
            ->where([
                'pra_date' => $today,
                'pra_p_id' => $data['pra_p_id'],
            ])
            ->count();
        $now = Db::table('up_plan_practice')
            ->where([
                'pra_status' => 2,
                'pra_date' => $today,
                'pra_p_id' => $data['pra_p_id'],
            ])
            ->count();
        $update = [
            'pra_status' => 2,
            'pra_url' => $pra_url
        ];
        $update['pra_minus'] = $data['pra_minus'] + $seconds;
        $update['pra_all_minus'] = $data['pra_all_minus'] + $seconds;
        $update['pra_times'] = $data['pra_times'] + 1;
        if($now + 1 == $all){
            $update['pra_days'] = $data['pra_days'] + 1;
        }
        $res = Db::table('up_plan_practice')
            ->where('pra_id',$pra_id)
            ->update($update);
        if($res){
            return json(['status'=>200,'msg'=>'提交成功']);
        }else{
            return json(['status'=>0,'msg'=>'提交失败，请刷新重试']);
        }
    }
}